package com.example.springbootdemo.config;

import com.example.springbootdemo.filter.CrossFilter;
import com.example.springbootdemo.interceptor.LoginInterceptor;
import com.example.springbootdemo.interceptor.RateLimitInterceptor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @Configuration 注解和 @Component 一样. 但是有特定应用场景
 * 在加了 @Configuration 这个注解类中, 写 @Bean
 * <beans>
 *     <bean id="user" class="com.example.springbootdemo.entity.User"></bean>
 * </beans>
 */
// @Component
@Configuration
@ConfigurationProperties(prefix = "cross")
public class WebConfig implements WebMvcConfigurer {

    private List<String> allowOrigin;

    public void setAllowOrigin(List<String> allowOrigin) {
        this.allowOrigin = allowOrigin;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RateLimitInterceptor()).addPathPatterns("/**");
        // 添加拦截器
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**");
    }
    /**
    @Bean
    public User user() {
        return new User();
    }
    */

    /**
     * springboot 中比较推崇的方式是,使用FilterRegistrationBean来注册我们的过滤器
     * <filter>
     *     <filter-name>filtername</filter-name>
     *     <filter-class>...XX</filter-class>
     * </filter>
     *
     * <filter-mapping>
     *     <filter-name>filtername</filter-name>
     *     <url-pattern>/*</url-pattern>
     * </filter-mapping>
     */
    // @Bean
    public FilterRegistrationBean<CrossFilter> filterFilterRegistrationBean() {
        FilterRegistrationBean<CrossFilter> bean = new FilterRegistrationBean<>();
        CrossFilter crossFilter = new CrossFilter();
        crossFilter.setAllowOrigin(allowOrigin);

        bean.setFilter(crossFilter);
        bean.setUrlPatterns(Arrays.asList("/*"));  //过滤器的过滤的资源
        bean.setOrder(1);

        return bean;
    }
}
